package cn.zhqr.lib.utils;

import cn.zhqr.lib.config.GlobalConfig;
import cn.zhqr.lib.config.Global;
import com.jfinal.kit.HashKit;
import com.jfinal.kit.LogKit;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.redis.Redis;
import com.jfinal.render.RenderException;
import org.apache.log4j.Logger;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;

public class ImgCodeKit {
    private static final Logger log = Logger.getLogger(ImgCodeKit.class);

    // 默认的验证码大小
    private static final int WIDTH = 108, HEIGHT = 40;

    public static void renderImgCode(Object sid, HttpServletResponse resp){
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

        String captcha = CaptchaKit.gene(image);
        log.info(sid+"生成验证码："+captcha);

        captcha = captcha.toUpperCase();
        captcha = HashKit.md5(captcha);

        if(StrKit.notBlank(captcha)){
            if(GlobalConfig.serverMode == Global.SERVER_MODE_PRO){
                Redis.use().setex(Global.mobile_verify_code.img_code+sid,30*60,captcha);
            }
        }

        ServletOutputStream sos = null;
        try {
            sos = resp.getOutputStream();
            ImageIO.write(image, "jpeg", sos);
        } catch (Exception e) {
            throw new RenderException(e);
        } finally {
            if (sos != null) {
                try {sos.close();} catch (IOException e) {
                    LogKit.logNothing(e);}
            }
        }
    }

    public static boolean valid(Object sid,String img_code){
        if(StrKit.isBlank(img_code)){
            return false;
        }

        String last_img_code = HashKit.md5("1234");
        if(GlobalConfig.serverMode == Global.SERVER_MODE_PRO){
            last_img_code = Redis.use().get(Global.mobile_verify_code.img_code+sid);
        }

        img_code = HashKit.md5(img_code.toUpperCase());

        return img_code.equals(last_img_code);

    }

}
